package com.huage_10.lesson_02;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/*
        反射获取构造方法并使用
 */
public class ReflectDemo01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //创建Student类的字节码文件对象
        Class<?> c = Class.forName("com.huage_10.lesson_02.Student");
        System.out.println("Student类中的公有方法：");
        Constructor<?>[] cons = c.getConstructors();
        for (Constructor<?> con : cons){
            System.out.println(con);
        }
        System.out.println("--------");

        System.out.println("Student类中的所有方法：");
        Constructor<?>[] dcons = c.getDeclaredConstructors();
        for (Constructor<?> dcon : dcons){
            System.out.println(dcon);
        }
        System.out.println("--------");

        //创建实例
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();
        System.out.println(obj);
        System.out.println("--------");

        Constructor<?> dCon1 = c.getDeclaredConstructor(String.class,int.class,String.class);
        Object obj1 = dCon1.newInstance("张三", 23, "北京");
        System.out.println(obj1);
        System.out.println("--------");

        Constructor<?> dCon2 = c.getDeclaredConstructor(String.class,String.class);
        Object obj2 = dCon2.newInstance("李四", "南京");
        System.out.println(obj2);
        System.out.println("--------");

        //暴力反射
        Constructor<?> dCon3 = c.getDeclaredConstructor(String.class);
        dCon3.setAccessible(true);
        Object obj3 = dCon3.newInstance("王五");
        System.out.println(obj3);
        System.out.println("--------");
    }
}
